package com.example.app12_data_storage.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app12_data_storage.R;

/**
 * 演示SharePreference
 * @author lijiguo
 */
public class SpActivity extends AppCompatActivity {

    private static final String TAG = "SpActivity";

    private EditText etSpKey;
    private EditText etSpValue;

    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sp);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.sp), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化控件
        etSpKey = findViewById(R.id.et_sp_key);
        etSpValue = findViewById(R.id.et_sp_value);

        sp = getSharedPreferences("data", Context.MODE_PRIVATE);
    }

    /**
     * 保存数据
     * @param view 发生点击事件的视图对象
     */
    public void save(View view) {
        SharedPreferences.Editor edit = sp.edit();
        String key = etSpKey.getText().toString();
        if (TextUtils.isEmpty(key)) {
            Toast.makeText(this, "数据的key不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        String value = etSpValue.getText().toString();
        if (TextUtils.isEmpty(value)) {
            Toast.makeText(this, "数据的value不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        edit.putString(key, value);
        // 已过时，官方建议使用 apply()
        // edit.commit();
        edit.apply();
        Toast.makeText(this, "保存完成!", Toast.LENGTH_SHORT).show();
    }

    /**
     * 读取数据
     * @param view 发生点击事件的视图对象
     */
    public void read(View view) {
        String key = etSpKey.getText().toString();
        if (TextUtils.isEmpty(key)) {
            Toast.makeText(this, "数据的key不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        String value = sp.getString(key, "没有获取到对应key的数据");
        if (TextUtils.isEmpty(value)) {
            Toast.makeText(this, "没有获取到对应key的数据！", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(this, "读取到的数据为: " + value, Toast.LENGTH_SHORT).show();
    }
}